import { mkdirSync, readdirSync, writeFileSync } from 'fs';
import { basename, join } from 'path';
import { commands, Uri, window, workspace } from 'vscode';
import { config, MessageFormat } from 'vscode-nls';
import generate from '../../util/generate';
import replace from '../../util/replace';

const localize = config({
	messageFormat: MessageFormat.file
})(__filename);

export default function add() {
	return commands.registerCommand('feidao.h5.component.add', async (uri: Uri) => {
		try {
			const path = uri.fsPath;
			// 如果当前目录不在某个页面中，则不允许操作
			const r = path.match(/[/\\](src-h5[/\\]\w[\w\d-]*)[/\\]?/);
			if (r === null) {
				window.showErrorMessage(localize(0));
			} else {
				const [, page_name] = r;
				const folder = join(workspace.getWorkspaceFolder(uri).uri.fsPath, page_name);

				const c = generate(folder, 'zj-', '', 6);
				// create
				mkdirSync(c);	// zj-000001
				create_tpl(c);
				create_s(c);
				create_ns(c);
				const id = basename(c);
				create_n(id, c);
				create_b(id, c);
				// update b.ts, n.ts
				const files = readdirSync(folder);
				const cs = files.filter((f) => {
					return /zj-\d{6}/.test(f);
				});
				await update_n(folder, cs);
				await update_b(folder, cs);
				await workspace.saveAll();
				window.showInformationMessage(localize(1));
				await workspace.saveAll();
			}
		} catch (error) {
			console.trace(error);
		}
	});
}

async function update_b(path: string, components: string[]) {
	// const eol = workspace.getConfiguration('files').get<string>('eol');
	const eol = '\n';
	const file_name = join(path, 'b.ts');
	const editor = await window.showTextDocument(Uri.file(file_name));

	const ims = components.map((c, i) => {
		return `import c${i} from './${c}/b';`;
	}).join(eol);
	await replace(editor, 'IMPCOMPONENTS', ims);

	const cs = components.map((_c, i) => {
		return `c${i}`;
	}).join(', ');
	if (cs.length > 0) {
		await replace(editor, 'COMPONENTS', `		,${cs}`);
	} else {
		await replace(editor, 'COMPONENTS', '');
	}
}

async function update_n(path: string, components: string[]) {
	// const eol = workspace.getConfiguration('files').get<string>('eol');
	const eol = '\n';
	const file_name = join(path, 'n.ts');
	const editor = await window.showTextDocument(Uri.file(file_name));

	const ims = components.map((c, i) => {
		return `import c${i} from './${c}/n';`;
	}).join(eol);
	await replace(editor, 'IMPCOMPONENTS', ims);

	const cs = components.map((_c, i) => {
		return `c${i}`;
	}).join(', ');
	if (cs.length > 0) {
		await replace(editor, 'COMPONENTS', `		,${cs}`);
	} else {
		await replace(editor, 'COMPONENTS', '');
	}
}

function create_b(id: string, path: string) {
	const tpl = `import init from '@feidao/web/framework/browser/d/component';

import s from './s';

/// FEIDAO IMPACTIONS BEGIN

/// FEIDAO IMPACTIONS END

export default function main(url: string, query: any) {
	/// FEIDAO ACTIONS BEGIN

	const actions = {};

	/// FEIDAO ACTIONS END
	return init('${id}', s, actions, url, query);
}
`;
	writeFileSync(join(path, 'b.ts'), tpl);
}

function create_n(id: string, path: string) {
	const tpl = `import { ICommonParams, IHeaders } from '@feidao/service/interfaces';
import { HTMLElement } from 'node-html-parser';
import s from './ns';

import init from '@feidao/web/framework/nodejs/d/component';

import tpl from './tpl';

/// FEIDAO IMPACTIONS BEGIN

/// FEIDAO IMPACTIONS END

export default function main(html: HTMLElement, url: string, msg: ICommonParams, headers: IHeaders, query: any) {

	/// FEIDAO ACTIONS BEGIN

	const actions = {};

	/// FEIDAO ACTIONS END


	return init('${id}', tpl, s, actions, html, url, msg, headers, query);
}

`;
	writeFileSync(join(path, 'n.ts'), tpl);
}

function create_ns(path: string) {
	const tpl = `export default {
};
`;
	writeFileSync(join(path, 'ns.ts'), tpl);
}

function create_s(path: string) {
	const tpl = `export default {
};
`;
	writeFileSync(join(path, 's.ts'), tpl);
}

function create_tpl(path: string) {
	const tpl = `export default \`
\`;
`;
	writeFileSync(join(path, 'tpl.ts'), tpl);
}
